// ==========================================
// 固定资产管理API接口
// ==========================================

// 获取资产分类列表
app.get('/api/asset/categories', async (req, res) => {
    try {
        const [rows] = await pool.execute(
            'SELECT * FROM asset_categories ORDER BY parent_id, sort_order'
        );
        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('获取分类失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 获取资产列表（支持筛选）
app.get('/api/assets', async (req, res) => {
    try {
        const { labId, categoryId, status, keyword, page = 1, pageSize = 20 } = req.query;

        let sql = 'SELECT a.*, c.name as category_name, l.name as lab_name FROM assets a LEFT JOIN asset_categories c ON a.category_id = c.id LEFT JOIN labs l ON a.lab_id = l.id WHERE 1=1';
        const params = [];

        if (labId) {
            sql += ' AND a.lab_id = ?';
            params.push(labId);
        }
        if (categoryId) {
            sql += ' AND a.category_id = ?';
            params.push(categoryId);
        }
        if (status) {
            sql += ' AND a.status = ?';
            params.push(status);
        }
        if (keyword) {
            sql += ' AND (a.asset_code LIKE ? OR a.name LIKE ?)';
            params.push(`%${keyword}%`, `%${keyword}%`);
        }

        sql += ' ORDER BY a.created_at DESC LIMIT ? OFFSET ?';
        params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize));

        const [rows] = await pool.execute(sql, params);
        res.json({ code: 0, success: true, data: { list: rows } });
    } catch (error) {
        console.error('获取资产列表失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 获取资产详情
app.get('/api/asset/:id', async (req, res) => {
    try {
        const { id } = req.params;

        const [rows] = await pool.execute(
            `SELECT a.*, c.name as category_name, l.name as lab_name 
             FROM assets a 
             LEFT JOIN asset_categories c ON a.category_id = c.id 
             LEFT JOIN labs l ON a.lab_id = l.id 
             WHERE a.id = ?`,
            [id]
        );

        if (rows.length === 0) {
            return res.json({ code: 2001, success: false, message: '资产不存在' });
        }

        // 获取维修历史
        const [repairs] = await pool.execute(
            'SELECT * FROM repair_orders WHERE asset_id = ? ORDER BY created_at DESC',
            [id]
        );

        res.json({
            code: 0,
            success: true,
            data: {
                ...rows[0],
                repairHistory: repairs
            }
        });
    } catch (error) {
        console.error('获取资产详情失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 添加资产（管理员）
app.post('/api/admin/asset/add', async (req, res) => {
    try {
        const {
            assetCode, name, categoryId, brand, model, specs,
            labId, location, purchaseDate, purchasePrice, supplier,
            warrantyPeriod, remark, adminKey
        } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!assetCode || !name) {
            return res.json({ code: 1001, success: false, message: '缺少必要参数' });
        }

        // 计算质保到期日
        let warrantyExpire = null;
        if (purchaseDate && warrantyPeriod) {
            const date = new Date(purchaseDate);
            date.setMonth(date.getMonth() + parseInt(warrantyPeriod));
            warrantyExpire = date.toISOString().split('T')[0];
        }

        await pool.execute(
            `INSERT INTO assets (
                asset_code, name, category_id, brand, model, specs,
                lab_id, location, purchase_date, purchase_price, supplier,
                warranty_period, warranty_expire, remark
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [
                assetCode, name, categoryId, brand, model, specs,
                labId, location, purchaseDate, purchasePrice, supplier,
                warrantyPeriod, warrantyExpire, remark
            ]
        );

        res.json({ code: 0, success: true, message: '添加成功' });
    } catch (error) {
        console.error('添加资产失败:', error);
        if (error.code === 'ER_DUP_ENTRY') {
            res.json({ code: 2002, success: false, message: '资产编号已存在' });
        } else {
            res.json({ code: 9999, success: false, message: '添加失败' });
        }
    }
});

// 更新资产（管理员）
app.put('/api/admin/asset/update', async (req, res) => {
    try {
        const {
            id, assetCode, name, categoryId, brand, model, specs,
            labId, location, purchaseDate, purchasePrice, supplier,
            warrantyPeriod, status, remark, adminKey
        } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!id) {
            return res.json({ code: 1001, success: false, message: '缺少资产ID' });
        }

        // 计算质保到期日
        let warrantyExpire = null;
        if (purchaseDate && warrantyPeriod) {
            const date = new Date(purchaseDate);
            date.setMonth(date.getMonth() + parseInt(warrantyPeriod));
            warrantyExpire = date.toISOString().split('T')[0];
        }

        const [result] = await pool.execute(
            `UPDATE assets SET 
                asset_code = ?, name = ?, category_id = ?, brand = ?, model = ?, specs = ?,
                lab_id = ?, location = ?, purchase_date = ?, purchase_price = ?, supplier = ?,
                warranty_period = ?, warranty_expire = ?, status = ?, remark = ?
             WHERE id = ?`,
            [
                assetCode, name, categoryId, brand, model, specs,
                labId, location, purchaseDate, purchasePrice, supplier,
                warrantyPeriod, warrantyExpire, status, remark, id
            ]
        );

        if (result.affectedRows === 0) {
            return res.json({ code: 2001, success: false, message: '资产不存在' });
        }

        res.json({ code: 0, success: true, message: '更新成功' });
    } catch (error) {
        console.error('更新资产失败:', error);
        res.json({ code: 9999, success: false, message: '更新失败' });
    }
});

// 删除资产（管理员）
app.delete('/api/admin/asset/delete', async (req, res) => {
    try {
        const { id, adminKey } = req.body;

        const ADMIN_SECRET_KEY = 'repair2024admin';
        if (adminKey !== ADMIN_SECRET_KEY) {
            return res.json({ code: 1003, success: false, message: '密钥错误' });
        }

        if (!id) {
            return res.json({ code: 1001, success: false, message: '缺少资产ID' });
        }

        // 检查是否有关联的报修单
        const [orders] = await pool.execute(
            'SELECT COUNT(*) as count FROM repair_orders WHERE asset_id = ?',
            [id]
        );

        if (orders[0].count > 0) {
            return res.json({
                code: 2003,
                success: false,
                message: `该资产有 ${orders[0].count} 条报修记录，无法删除`
            });
        }

        const [result] = await pool.execute('DELETE FROM assets WHERE id = ?', [id]);

        if (result.affectedRows === 0) {
            return res.json({ code: 2001, success: false, message: '资产不存在' });
        }

        res.json({ code: 0, success: true, message: '删除成功' });
    } catch (error) {
        console.error('删除资产失败:', error);
        res.json({ code: 9999, success: false, message: '删除失败' });
    }
});

// 资产统计
app.get('/api/asset/stats', async (req, res) => {
    try {
        const [stats] = await pool.execute(`
            SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'in_use' THEN 1 ELSE 0 END) as in_use,
                SUM(CASE WHEN status = 'idle' THEN 1 ELSE 0 END) as idle,
                SUM(CASE WHEN status = 'repairing' THEN 1 ELSE 0 END) as repairing,
                SUM(CASE WHEN status = 'scrapped' THEN 1 ELSE 0 END) as scrapped,
                SUM(IFNULL(purchase_price, 0)) as total_value
            FROM assets
        `);

        res.json({ code: 0, success: true, data: stats[0] });
    } catch (error) {
        console.error('获取统计失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});

// 按机房统计资产
app.get('/api/asset/stats/by-lab', async (req, res) => {
    try {
        const [stats] = await pool.execute(`
            SELECT 
                l.id, l.name,
                COUNT(a.id) as asset_count,
                SUM(IFNULL(a.purchase_price, 0)) as total_value
            FROM labs l
            LEFT JOIN assets a ON l.id = a.lab_id
            GROUP BY l.id, l.name
            ORDER BY asset_count DESC
        `);

        res.json({ code: 0, success: true, data: { list: stats } });
    } catch (error) {
        console.error('获取机房统计失败:', error);
        res.json({ code: 9999, success: false, message: '查询失败' });
    }
});
